package com.zbs.framework.chat.config;

import com.zbs.framework.chat.constants.WebSocketConstants;
import com.zbs.framework.chat.customer.WebSocketRedisSubscriber;
import com.zbs.framework.common.redis.RedisCondition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Configuration
@Conditional(RedisCondition.class)
public class WebsocketRedisMQConfig {

    /**
     * 消息监听器，使用MessageAdapter可实现自动化解码及方法代理
     *
     * @return
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // 可以添加多个 messageListener，配置不同的交换机
        container.addMessageListener(listenerAdapter, new PatternTopic(WebSocketConstants.REDIS_CHANNEL));// 订阅最新消息频道
        return container;
    }

    @Bean
    public MessageListenerAdapter listenerAdapter(WebSocketRedisSubscriber webSocketRedisSubscriber) {
        // 消息监听适配器
        return new MessageListenerAdapter(webSocketRedisSubscriber, "onMessage");
    }
}